/**
 * a class for uav
 * a class manage uavs
 */

class Uav {
    constructor(uaven) {
        this._en = uaven;
        this._posid = null;
        this._posidLast = null;
        this._posidNext = null;
        this._priority = uaven.priority;
    }

    /**
     * @param {Function} cb
     */
    set gridChange(cb) {
        this._gridchangeCB = cb;
    }

    Grid(posid) {
        if (this._posid !== posid) {
            if (this._gridchangeCB) this._gridchangeCB(this._posid, posid);
            this._posidLast = this._posid;
            this._posid = posid;
        }
    }

    NextGrid(posid) {
        this._posidNext = posid;
    }

    Pause() {
        this._en.position.Pause = true;
    }

    Resume() {
        this._en.position.Pause = false;
    }
}

class UavManager {
    constructor() {
        this._codemap = new Map();
    }

    Clear(){
        this._codemap.clear();
    }

    AddGrid(posid, u) {
        const cm = this._codemap;
        if (this._codemap.has(posid)) {
            u.gridChange = (oldposid, _) => {
                if (oldposid === posid) {
                    // means the uav leaf this grid, shoud pop
                    const cmg = cm.get(posid);
                    const idx = cmg.indexOf(u);
                    cmg.splice(idx, 1);
                    // other uav in this grid should resume
                    if (cmg.length === 0) {
                        cm.delete(posid);
                    } else {
                        cmg[0].Resume();
                    }
                }
            }

            const us = this._codemap.get(posid);
            if (us.indexOf(u) === -1) {
                u.Pause();
                us.push(u);
                us.sort((a, b) => b._priority - a._priority);
            }
        }
        else {
            const us = [];
            this._codemap.set(posid, us);
            if (!!u) {
                u.Pause();
                us.push(u);
            }
        }
    }

    Refresh() {
        for (const k of this._codemap.keys()) {
            const us = this._codemap.get(k);
            if (us.length > 0) {
                us[0].Resume();
            }
        }
    }
}

export { UavManager, Uav };